4.6 kotlin.Unit类型

Kotlin也是面向表达式的语言。在Kotlin中所有控制流语句都是表达式(除了变量赋值、异常等)。

Kotlin中的Unit类型实现了与Java中的void一样的功能。不同的是,当一个函数没有返回值的时候,我们用Unit来表示这个特征,而不是null

大多数时候,我们并不需要显式地返回Unit,或者声明一个函数的返回类型为Unit。编译器会推断出它。

代码示例:

  1. >>> fun unitExample(){println("Hello,Unit")}
  2. >>> val helloUnit = unitExample()
  3. Hello,Unit
  4. >>> helloUnit
  5. kotlin.Unit
  6. >>> println(helloUnit)
  7. kotlin.Unit

下面几种写法是等价的:

  1. @RunWith(JUnit4::class)
  2. class UnitDemoTest {
  3. @Test fun testUnitDemo() {
  4. val ur1 = unitReturn1()
  5. println(ur1) // kotlin.Unit
  6. val ur2 = unitReturn2()
  7. println(ur2) // kotlin.Unit
  8. val ur3 = unitReturn3()
  9. println(ur3) // kotlin.Unit
  10. }
  11. fun unitReturn1() {
  12. }
  13. fun unitReturn2() {
  14. return Unit
  15. }
  16. fun unitReturn3(): Unit {
  17. }
  18. }

总的来说,这个Unit类型并没有什么特别之处。它的源码是:

  1. package kotlin
  2. /**
  3. * The type with only one value: the Unit object. This type corresponds to the `void` type in Java.
  4. */
  5. public object Unit {
  6. override fun toString() = "kotlin.Unit"
  7. }

跟任何其他类型一样,它的父类型是Any。如果是一个可空的Unit?,它的父类型是Any?

Kotlin极简教程